import axios from 'axios'
import {
    Message
} from 'element-ui'
import store from '@/store'
import {
    getToken
} from '@/utils/auth'

const instance = axios.create({
    // baseURL: 'http://122.51.249.55:7001/', // api的base_url
    baseURL: 'http://localhost:7001/',
    timeout: 5000 // request timeout
})

// 影响拦截器
instance.interceptors.request.use(
    config => {
        if (store.getters.token) {
            // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
            config.headers.Authorization = `Bearer ${getToken()}`
        }
        return config
    },
    error => {
        Promise.reject(error)
    }
)

// 响应拦截器
instance.interceptors.response.use(
    response => response,
    error => {
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export const createAPI = (url, method, data) => {
    const config = {}
    if (method === 'get') {
        config.params = data
    } else {
        config.data = data
    }
    return instance({
        url,
        method,
        ...config
    })
}

export const createFormAPI = (url, method, data) => {
    const config = {}
    config.data = data
    config.headers = {
        'Cache-Control': 'no-cache',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    config.responseType = 'json'
    config.transformRequest = [
        function(data) {
            let ret = ''
            for (const it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            return ret
        }
    ]
    return instance({
        url,
        method,
        ...config
    })
}